
//
//  DoorSystemPushSelectViewController.m
//  RONGAO
//
//  Created by ZhangYeKun on 2017/2/24.
//  Copyright © 2017年 wei wang. All rights reserved.
//

#import "DoorSystemPushSelectViewController.h"
#import "DSPushSelectTableViewCell.h"
@interface DoorSystemPushSelectViewController ()<UITableViewDelegate,UITableViewDataSource,MyCameraDelegate>{
    
    NSInteger motionDetection;
    NSInteger pushNotification;

}
/** tableView **/
@property(nonatomic,strong) UITableView *tableView;

/** camera **/
@property(nonatomic,strong) MyCamera *camera;

@end

@implementation DoorSystemPushSelectViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self setNavigationStyle];
    self.camera = [AppDelegate globalDelegate].cameraModel;
    motionDetection = -1;
    pushNotification = -1;

    [self getMotioneDetectionInfo];
    [self armingSMsgAVIoctrlGet:self.camera];
    
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];

    if (self.camera != nil)
        self.camera.delegate2 = self;
#if defined(P2PBANDIANGOU) || defined(P2PWEXVS) || defined(P2PAUROCAM_WEX)
    pushNotification = self.camera.isPushMode;
#else
    pushNotification = [self readSQListPushNotification];
#endif

}
#pragma mark - --------------------------获取推送设置--------------------------
- (void)getMotioneDetectionInfo{
    
    // get MotionDetection info
    SMsgAVIoctrlGetMotionDetectReq *structMotionDetection = malloc(sizeof(SMsgAVIoctrlGetMotionDetectReq));
    memset(structMotionDetection, 0, sizeof(SMsgAVIoctrlGetMotionDetectReq));
    
    structMotionDetection->channel = 0;
    [self.camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_GETMOTIONDETECT_REQ
                           Data:(char *)structMotionDetection
                       DataSize:sizeof(SMsgAVIoctrlGetMotionDetectReq)];
    free(structMotionDetection);

    
}

#pragma mark - --------------------------获取布防撤防--------------------------
- (void)armingSMsgAVIoctrlGet:(MyCamera *)camera
{
    NSLog(@"armingSMsgAVIoctrlGet");
    SMsgAVIoctrlThirdpartReq *structArming = (SMsgAVIoctrlThirdpartReq *)malloc(sizeof(SMsgAVIoctrlThirdpartReq));
    memset(structArming, 0, sizeof(SMsgAVIoctrlThirdpartReq));
    
    structArming->command_types_ = THIRD_PART_GET_ALARMED_STATUS;
    
    [camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_THIRDPART_SETTING_REQ
                           Data:(char *)structArming
                       DataSize:sizeof(SMsgAVIoctrlThirdpartReq)];
    free(structArming);
}

- (void)armingSMsgAVIoctrlSet:(MyCamera *)camera
{
    SMsgAVIoctrlThirdpartReq *s = (SMsgAVIoctrlThirdpartReq *)malloc(sizeof(SMsgAVIoctrlThirdpartReq));
    memset(s, 0, sizeof(SMsgAVIoctrlThirdpartReq));
    
    s->command_types_ = THIRD_PART_SET_ALARMED_STATUS;
    s->value1_ = (int)camera.newArming;
    
    [camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_THIRDPART_SETTING_REQ
                           Data:(char *)s
                       DataSize:sizeof(SMsgAVIoctrlThirdpartReq)];
    
    free(s);
    
}


#pragma mark

- (int)getMotionDetectionSettingRowIndex
{
    return [self.camera getMotionDetectionSettingSupportOfChannel:0] ? 0 : -1;
}

#pragma mark

- (int)getEventSettingSectionIndex
{
    int idx = 0;
    
    return [self.camera getMotionDetectionSettingSupportOfChannel:0] ? idx : -1;
}



#pragma mark - --------------------------UITableView dataSource--------------------------

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 3;
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DSPushSelectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kDSPushSelectIdentifier];
    if (cell == nil) {
        
        cell = [[DSPushSelectTableViewCell alloc]init];
        
    }
    __weak typeof(self) weakself = self;
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    switch (indexPath.row) {
        case 0:
        {
            if (pushNotification == 0){
                
                [cell.switchControl setOn:NO];
                
            }else if (pushNotification == 1){
                
                [cell.switchControl setOn:YES];
                
            }

            cell.textLabel.text = @"门铃触发";
            cell.detailTextLabel.text = @"当有人按门铃，推送提醒";
            
            cell.SwitchBlock = ^(UISwitch *Switch){
                
                if (Switch.isOn == YES) {//开启推送
                    
                    [self writeSQListPushNotification:1];
                    pushNotification = 1;
                    [self readSQListPushNotification];

                }else if (Switch.isOn == NO){//关闭推送
                    
                    [self writeSQListPushNotification:0];
                    pushNotification = 0;
                    [self readSQListPushNotification];

                }
                
            };
            break;
        }
        case 1:
        {
            if (motionDetection == 0){
                
                [cell.switchControl setOn:NO];
  
            }else if (motionDetection > 0){
                
                [cell.switchControl setOn:YES];
  
            }
            
            
            cell.SwitchBlock = ^(UISwitch *Switch){ //开启 75newValue
                if (weakself.camera != nil && weakself.camera.sessionState == CONNECTION_STATE_CONNECTED && [weakself.camera getConnectionStateOfChannel:0] == CONNECTION_STATE_CONNECTED) {
                
                    if (Switch.isOn == YES) {
                        SMsgAVIoctrlSetMotionDetectReq *structSetMotionDetection = malloc(sizeof(SMsgAVIoctrlSetMotionDetectReq));
                        memset(structSetMotionDetection, 0, sizeof(SMsgAVIoctrlSetMotionDetectReq));
                        
                        motionDetection = 1;
                        structSetMotionDetection->channel = 0;
                        structSetMotionDetection->sensitivity = 75;
                        
                        [weakself.camera sendIOCtrlToChannel:0
                                                        Type:IOTYPE_USER_IPCAM_SETMOTIONDETECT_REQ
                                                        Data:(char *)structSetMotionDetection
                                                    DataSize:sizeof(SMsgAVIoctrlSetMotionDetectReq)];
                        
                        free(structSetMotionDetection);
                        
                    }else if (Switch.isOn == NO){
                        
                        SMsgAVIoctrlSetMotionDetectReq *structSetMotionDetection = malloc(sizeof(SMsgAVIoctrlSetMotionDetectReq));
                        memset(structSetMotionDetection, 0, sizeof(SMsgAVIoctrlSetMotionDetectReq));
                        
                        structSetMotionDetection->channel = 0;
                        structSetMotionDetection->sensitivity = 0;
                        motionDetection = 0;

                        [weakself.camera sendIOCtrlToChannel:0
                                                        Type:IOTYPE_USER_IPCAM_SETMOTIONDETECT_REQ
                                                        Data:(char *)structSetMotionDetection
                                                    DataSize:sizeof(SMsgAVIoctrlSetMotionDetectReq)];
                        
                        free(structSetMotionDetection);
                        
                    }

                }else{
                    
                    [weakself.tableView reloadData];
                }
                
                
               
                
            };
            cell.textLabel.text = @"移动侦查";
            cell.detailTextLabel.text = @"侦测到人体在门口停留15秒，推送提醒";
            break;
        }
        case 2:
        {
            
            
            if (self.camera.orgArming == 0) {
                
                [cell.switchControl setOn:NO];

            }else if(self.camera.orgArming == 1){
                
                [cell.switchControl setOn:YES];

            }
            cell.textLabel.text = @"报警器布防";
            cell.detailTextLabel.text = @"当报警器被触发，推送提醒";
            
            cell.SwitchBlock = ^(UISwitch *Switch){
                
                if (weakself.camera != nil && weakself.camera.sessionState == CONNECTION_STATE_CONNECTED && [weakself.camera getConnectionStateOfChannel:0] == CONNECTION_STATE_CONNECTED) {
                    
                    //if ([camera getDeviceIRCutSupportOfChannel:0]){
                    //if ([camera getDeviceArmSupportOfChannel:0]) {
                    if(TRUE)
                    {
                        NSLog(@"camera.orgArming:%ld, camera.newArming:%ld", (long)weakself.camera.orgArming, (long)weakself.camera.newArming);
                        
                        if (weakself.camera.orgArming < 0) {
                            [weakself armingSMsgAVIoctrlGet:weakself.camera];
                        } else {
                            if (weakself.camera.orgArming > 0) {
                                weakself.camera.newArming = 0;
                            } else {
                                weakself.camera.newArming = 1;
                            }
                            
                            weakself.camera.orgArming = -1;
                            [weakself armingSMsgAVIoctrlSet:weakself.camera];
                            
                            [weakself.tableView reloadData];
                        }
                        
                    } else {
                        [SVProgressHUD showInfoWithStatus:@"这个设备不支持此操作"];
            
                    }
                    
                } else {
                    [SVProgressHUD showInfoWithStatus:@"设备离线"];
                    
                        [weakself.tableView reloadData];
                }

            };
            break;
        }
        default:
            break;
    }
    
    return cell;
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 60.f;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
    
}
#pragma mark - --------------------------UITableView delegate--------------------------

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
}


#pragma mark - MyCameraDelegate Methods
- (void)camera:(MyCamera *)camera_ _didReceiveIOCtrlWithType:(NSInteger)type Data:(const char *)data DataSize:(NSInteger)size {
    
    if (camera_ == self.camera) {
    
        #pragma mark - --------------------------布防撤防--------------------------
        
        if (type == IOTYPE_USER_IPCAM_GETMOTIONDETECT_RESP) {
            
            SMsgAVIoctrlGetMotionDetectResp *s = (SMsgAVIoctrlGetMotionDetectResp*)data;
            motionDetection = s->sensitivity;
            
            [self.tableView reloadData];
        }
        
        if (type == IOTYPE_USER_IPCAM_THIRDPART_SETTING_RESP) {//
            SMsgAVIoctrlThirdpartResp *s = (SMsgAVIoctrlThirdpartResp*)data;
            NSLog(@"IOTYPE_USER_IPCAM_THIRDPART_SETTING_RESP s->command_types_:%d, s->result_:%d, s->value_:%d",
                  s->command_types_, s->result_, s->value_);
            if (THIRD_PART_GET_ALARMED_STATUS == s->command_types_) {
                //[[iToast makeText:NSLocalizedString(@"IR Correct Success", @"")]show];
                
                if (0 == s->result_) {
                    NSLog(@"camera_.orgArming:%ld, camera_.newArming:%ld",
                          (long)camera_.orgArming, (long)camera_.newArming);
                    //if (camera_.orgArming < 0)
                    {
                        camera_.orgArming = s->value_;
                        camera_.newArming = s->value_;
                        
                        [self.tableView reloadData];
                        
                    }
                } else {
                }
                
                
            } else if (THIRD_PART_SET_ALARMED_STATUS == s->command_types_) {
                //[[iToast makeText:NSLocalizedString(@"IR Correct Fail", @"")]show];
                
                if (0 == s->result_) {
                    camera_.orgArming = s->value_;
                    NSString *arm;
                    if (camera_.orgArming) {
                        arm = NSLocalizedString(@"Arming", @"");
                    } else {
                        arm = NSLocalizedString(@"Disarming", @"");
                    }
                    NSString *showStr = [NSString stringWithFormat:@"%@  %@", camera_.name, arm];
                    
                    //  [[iToast makeText:showStr]show];
                    
                    [self.tableView reloadData];
                    
                } else {
                    NSString *arm;
                    if (camera_.newArming) {
                        arm = NSLocalizedString(@"Arming", @"");
                    } else {
                        arm = NSLocalizedString(@"Disarming", @"");
                    }
                    NSString *showStr = [NSString stringWithFormat:@"%@  %@ Fail", camera_.name, arm];
                    
                    //   [[iToast makeText:showStr]show];
                    
                    [self.tableView reloadData];
                    
                }
                
            }
        }

    }
    
    
}


#pragma mark - SQList (push_notification) Methods
- (NSInteger)readSQListPushNotification
{
    
    NSInteger push_notification = -1;
    
    FMResultSet *rs = [[AppDelegate globalDelegate].database executeQuery:@"SELECT * FROM notification WHERE dev_uid=?", self.camera.uid];
    
    while([rs next]) {
        push_notification = [rs intForColumn:@"push_notification"];
        NSLog(@"UID(%@) push_notification:%ld", self.camera.uid, (long)push_notification);
    }
    [rs close];
    
    
#if defined(P2PWEXVS) || defined(P2PAUROCAM_WEX)
    if (push_notification < 0) {
        [self initSQListPushNotificationToUID:camera.uid];
        
        push_notification = 1;
    }
#else
#endif
    
    
    return push_notification;
}

- (void)writeSQListPushNotification:(NSInteger)push_notification
{
    if ([AppDelegate globalDelegate].database != NULL) {
        
        if (push_notification == 0) {
            
            [AppDelegate globalDelegate].cameraModel.isPushMode = 0;
            if (![[AppDelegate globalDelegate].database executeUpdate:@"UPDATE notification SET push_notification=? WHERE dev_uid=?", [NSNumber numberWithInt:0], self.camera.uid]) {
                NSLog(@"Fail to update device to database.");
            }
        }else if (push_notification == 1){
            [AppDelegate globalDelegate].cameraModel.isPushMode = 1;

            if (![[AppDelegate globalDelegate].database executeUpdate:@"UPDATE notification SET push_notification=? WHERE dev_uid=?", [NSNumber numberWithInt:1], self.camera.uid]) {
                NSLog(@"Fail to update device to database.");
            }
        }
        
       
    }
}

- (void)initSQListPushNotificationToUID:(NSString *)uid {
    if ([AppDelegate globalDelegate].database != NULL) {
        [[AppDelegate globalDelegate].database executeUpdate:@"INSERT INTO notification(dev_uid, push_notification) VALUES(?,?)",
         uid, [NSNumber numberWithInt:1]];
    }
}

- (UITableView *)tableView{
    
    if (!_tableView) {
        
        __weak UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [superView addSubview:_tableView];
        //        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;//隐藏tableView的分割线
        _tableView.scrollEnabled = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    
    return _tableView;
    
}


- (void)setNavigationStyle{
    
    [self setLeftButtonImage:[UIImage imageNamed:@"icon_back_nor"]];
    [self setNavigationTitle:@"推送选择" titleColor:[UIColor colorWithRed:210/255.0 green:177/255.0 blue:104/255.0 alpha:1]];
    
}

- (void)masLayoutSubview{
    
    __weak UIView *superView = self.view;
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(superView);
        
    }];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
